<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 输入框 -->
      <el-row :gutter="30">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserListAll" @keyup.enter.native="getUserListAll">
            <el-button slot="append" icon="el-icon-search" @click="getUserListAll"></el-button>
          </el-input>
        </el-col>

        <el-col :span="5">
          <el-button type="primary" @click="addUserDialogVisiable = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 渲染表格 -->
      <el-table :data="userList" border>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-tooltip enterable content="修改用户" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditUserDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip enterable content="删除用户" placement="top">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip enterable content="分配角色" placement="top">
              <el-button size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[2, 3, 5]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="addUserDialogVisiable" width="50%" @close="closedDialog('addUser')">
      <el-form :model="addUserForm" :rules="addUserFormrules" ref="addUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input clearable v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input clearable v-model="addUserForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input clearable v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input clearable v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editUserDialogVisiable" width="50%" @close="closedEditUserDialog('editUser')">
      <el-form :model="editUserForm" :rules="editUserFormrules" ref="editUserFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input clearable v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input clearable v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+([a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) return callback();

      callback(new Error('请输入正确的邮箱'));
    };
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) return callback();

      callback(new Error('请输入正确的手机号'));
    };
    return {
      // 用户数据列表
      userList: [],
      // 获取用户列表的查询参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 数据总数目
      total: 0,
      // 修改用户对话款显示隐藏控制值
      editUserDialogVisiable: false,
      // 修改用户表单数据对象
      editUserForm: {},
      // 修改用户表单数据验证规则对象
      editUserFormrules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 添加用户对话款显示隐藏控制值
      addUserDialogVisiable: false,
      // 添加用户表单数据对象
      addUserForm: {
        username: 'lkl',
        password: '123456',
        email: '123@qq.com',
        mobile: '15844548687'
      },
      // 添加用户表单数据验证规则对象
      addUserFormrules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3到10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 12, message: '密码在6到12个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取用户数据列表
    async getUserList() {
      const res = await this.$axios.get('users', { params: this.queryInfo });
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败！');
      this.total = res.data.total;
      this.userList = res.data.users;
    },

    // 查询全部数据
    async getUserListAll() {
      const res = await this.$axios.get('users', {
        params: {
          query: this.queryInfo.query,
          pagenum: 1,
          pagesize: 2
        }
      });
      if (res.meta.status !== 200) return this.$message.error('查询用户失败！');
    },

    // 修改用户状态
    async changeState(row) {
      // console.log(row);
      const res = await this.$axios.put(`users/${row.id}/state/${row.mg_state}`);

      if (res.meta.status !== 200) return this.$message.error('修改用状态失败！');
      this.$message.success('修改用状态成功！');
    },

    //  每页显示数据条数发生变化的事件函数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },

    //  页码值发生变化的事件函数
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum;
      this.getUserList();
    },

    // 删除用户
    async deleteUser(id) {
      // 弹出删除提示框
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error);

      // console.log(confirmResult);
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除操作！');

      const res = await this.$axios.delete('users/' + id);
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！');

      this.$message.success('删除用户成功！');
      // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
      const totalPage = Math.ceil((this.total - 1) / this.queryInfo.pagesize) // 总页数
      this.queryInfo.pagenum = this.queryInfo.pagenum > totalPage ? totalPage : this.queryInfo.pagenum;
      this.queryInfo.pagenum = this.queryInfo.pagenum < 1 ? 1 : this.queryInfo.pagenum;
      this.getUserList();
    },

    // 显示修改用户对话框，并查询用户
    async showEditUserDialog(id) {
      const res = await this.$axios.get('users/' + id);
      if (res.meta.status !== 200) return this.$message.error('查询用户信息失败！');

      this.editUserForm = res.data;
      console.log(this.editUserForm);
      this.editUserDialogVisiable = true;
    },

    // 关闭对话框事件，重置表单
    closedDialog(dialogName) {
      if (dialogName === 'editUser') {
        this.$refs.editUserFormRef.resetFields();
      } else if (dialogName === 'addUser') {
        this.$refs.addUserFormRef.resetFields();
      }
    },

    // 确定修改用户信息
    editUser() {
      // 表单数据预验证
      this.$refs.editUserFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return this.$message.error('请正确填写表单项');

        const res = await this.$axios.put('users/' + this.editUserForm.id, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        });

        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败！');
        this.$message.success('修改用户信息成功！');
        this.getUserList();
        this.editUserDialogVisiable = false;
      });
    },

    // 添加用户事件
    addUser() {
      // 表单数据预验证
      this.$refs.addUserFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return this.$message.error('请正确填写表单项');

        const res = await this.$axios.post('users', this.addUserForm);

        if (res.meta.status !== 201) return this.$message.error('添加用户失败！');
        this.$message.success('添加用户成功！');
        this.getUserList();
        this.addUserDialogVisiable = false;
      });
    }
  },
  created() {
    this.getUserList();
  },
}
</script>

<style lang="less" scoped>
</style>